package com.lvmama.controller.rhino.page;

import com.github.pagehelper.PageInfo;
import com.lvmama.common.enums.CommonParentType;
import com.lvmama.common.result.Result;
import com.lvmama.pojo.dto.rhino.page.PageAnalysisDTO;
import com.lvmama.pojo.dto.rhino.page.FlowStatisticsVo;
import com.lvmama.pojo.entity.rhino.topic.StatisticCode;
import com.lvmama.service.rhino.page.FlowStatisticsService;
import com.lvmama.service.rhino.topic.StatisticCodeService;
import com.lvmama.utils.ToolUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.*;

@Controller
@RequestMapping("/traffic")
@Slf4j
public class TrafficController {

    @Autowired
    private StatisticCodeService statisticCodeService;
    @Autowired
    private FlowStatisticsService flowStatisticsService;


    @PostMapping("/regionData")
    @ResponseBody
    public Result<Map<String, Object>> regionData(@RequestBody PageAnalysisDTO pageAnalysisDTO){
        // 处理起始日期
        Map<String, Date> dateMap = ToolUtils.getQueryDate(pageAnalysisDTO.getChooseTime());
        Date startDate = dateMap.get("beginDate");
        Date endDate = dateMap.get("endDate");
        Map<String, Object> retMap = new HashMap<String, Object>();
        // 获取平台相关code
        List<String> statisticCodeList = getPlatform(pageAnalysisDTO.getPlat_form());
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("start_date", startDate);
        param.put("end_date", endDate);
        String code = "";
        if ("internalFlow".equals(pageAnalysisDTO.getFlow_type())) {
            param.put("plat_form", pageAnalysisDTO.getPlat_form());
            code = "11";
        } else if ("outFlow".equals(pageAnalysisDTO.getFlow_type())) {
            // 如果渠道1不选择 筛选全部外部渠道code
            if (pageAnalysisDTO.getChannel1() == "") {
                code = "12";
            } else {
                // 如果渠道2不选 删选渠道1所有子集code
                if (pageAnalysisDTO.getChannel2() == "") {
                    code = pageAnalysisDTO.getChannel1().split("_")[1];
                } else {
                    code = pageAnalysisDTO.getChannel2().split("_")[1];
                }
            }
        }
        List<String> channelCodeList = statisticCodeService.getChannelCode(code);
        param.put("statisticCodeList", statisticCodeList.size() == 0 ? null : statisticCodeList);// 平台code
        param.put("channelCodeList", channelCodeList);// 渠道code

        // //////////////////////地区分布图数据处理开始////////////////
        List<FlowStatisticsVo> landingRegionList = flowStatisticsService.landingRegionData(param);
        Map<String, Long> regionPreMap = new HashMap<>();
        List<String> regionList = new ArrayList<>();
        for (FlowStatisticsVo landingRegion : landingRegionList) {
            regionPreMap.put(landingRegion.getRegionCode(), landingRegion.getAmount());
        }
        // 获取前十条数据
        regionPreMap = ToolUtils.sortByValueDesc(regionPreMap);
        Map<String, Long> regionMap = new HashMap<>();
        int index = 0;
        long otherAmount = 0;
        for (Map.Entry<String, Long> entry : regionPreMap.entrySet()) {
            if (index < 10) {
                regionList.add(entry.getKey());
                regionMap.put(entry.getKey(), entry.getValue());
            } else {
                otherAmount += entry.getValue();
            }
            index++;
        }
        if (regionPreMap.size() > 10) {
            regionList.add("其他");
            regionMap.put("其他", otherAmount);
        }
        retMap.put("regionMap", regionMap);
        retMap.put("regionList", regionList);

        // //////////////////////地区分布图数据处理结束////////////////
        return Result.success(retMap);
    }


    /**
     * 着陆页流量-着陆页详情
     *
     * @return
     * @throws Exception
     */
    @PostMapping("/landingPage")
    @ResponseBody
    public Result<Map<String, Object>>  landingPageData(@RequestBody PageAnalysisDTO pageAnalysisDTO){
        int defaultLength = 10;
        // 处理起始日期
        Map<String, Date> dateMap = ToolUtils.getQueryDate(pageAnalysisDTO.getChooseTime());
        Date startDate = dateMap.get("beginDate");
        Date endDate = dateMap.get("endDate");
        Map<String, Object> retMap = new HashMap<String, Object>();
        String[] depthxAxis = new String[defaultLength];
        Long[] depthseries = new Long[defaultLength];
        String[] timexAxis = new String[defaultLength];
        Long[] timeseries = new Long[defaultLength];

        // 获取平台相关code
        List<String> statisticCodeList = getPlatform(pageAnalysisDTO.getPlat_form());
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("start_date", startDate);
        param.put("end_date", endDate);
        String code = "";
        if ("internalFlow".equals(pageAnalysisDTO.getFlow_type())) {
            param.put("plat_form", pageAnalysisDTO.getPlat_form());
            code = "11";
        } else if ("outFlow".equals(pageAnalysisDTO.getFlow_type())) {
            // 如果渠道1不选择 筛选全部外部渠道code
            if (StringUtils.isEmpty(pageAnalysisDTO.getChannel1())) {
                code = "12";
            } else {
                // 如果渠道2不选 删选渠道1所有子集code
                if (StringUtils.isEmpty(pageAnalysisDTO.getChannel2())) {
                    code = pageAnalysisDTO.getChannel1().split("_")[1];
                } else {
                    code = pageAnalysisDTO.getChannel2().split("_")[1];
                }
            }
        }
        List<String> channelCodeList = statisticCodeService
                .getChannelCode(code);
        param.put("statisticCodeList", statisticCodeList.size() == 0 ? null
                : statisticCodeList);// 平台code
        param.put("channelCodeList", channelCodeList);// 渠道code

        Map<String, List<FlowStatisticsVo>> resultMap = flowStatisticsService.landingPageDepthTime(param);
        List<FlowStatisticsVo> accessTimeMap = resultMap.get("AccessTime");
        List<FlowStatisticsVo> depthMap = resultMap.get("Depth");
        List<FlowStatisticsVo> landingPageMap = resultMap.get("LandingPage");

        long accessAmount = 0l;
        long timeAmount = 0l;
        for (FlowStatisticsVo flowStatisticsVo : accessTimeMap) {
            if (flowStatisticsVo != null && flowStatisticsVo.getDuration() < 0) {
                flowStatisticsVo.setDuration(Math.abs(flowStatisticsVo.getDuration()));
            }
            accessAmount += flowStatisticsVo.getAmount();
            timeAmount += flowStatisticsVo.getDuration() * flowStatisticsVo.getAmount();
        }
        Collections.sort(accessTimeMap, new Comparator<FlowStatisticsVo>() {
            @Override
            public int compare(FlowStatisticsVo o1, FlowStatisticsVo o2) {
                return o1.getDuration() >= o2.getDuration() ? 1 : -1;
            }
        });

        if (accessTimeMap != null && !accessTimeMap.isEmpty()) {
            Long sum = 0l;
            for (int i = 0; i < accessTimeMap.size(); i++) {
                if (i < defaultLength - 1) {
                    timexAxis[i] = accessTimeMap.get(i).getDuration() * 30 + "";
                    timeseries[i] = accessTimeMap.get(i).getAmount();
                } else if (i == accessTimeMap.size() - 1) {
                    timexAxis[defaultLength - 1] = accessTimeMap.get(defaultLength - 1).getDuration() * 30 + "+";
                    timeseries[defaultLength - 1] = sum + accessTimeMap.get(i).getAmount();
                } else {
                    sum += accessTimeMap.get(i).getAmount();
                }
            }
        }
        long depthAmount = 0l;
        long sessionAmount = 0l;
        if (depthMap != null && !depthMap.isEmpty()) {
            Long sum = 0l;
            for (int i = 0; i < depthMap.size(); i++) {
                depthAmount += depthMap.get(i).getDepth() * depthMap.get(i).getAmount();
                sessionAmount += depthMap.get(i).getAmount();
                if (i < defaultLength - 1) { depthxAxis[i] = depthMap.get(i).getDepth() + "";depthseries[i] = depthMap.get(i).getAmount();
                } else if (i == depthMap.size() - 1) {
                    depthxAxis[defaultLength - 1] = depthMap.get(defaultLength - 1).getDepth() + "+";depthseries[defaultLength - 1] = sum + depthMap.get(i).getAmount();
                } else {
                    sum += depthMap.get(i).getAmount();
                }
            }
        }
        Long amount = 0l;
        Long bounce_amount = 0l;
        if (landingPageMap != null && !landingPageMap.isEmpty()) {
            FlowStatisticsVo flowStatistics = landingPageMap.get(0);
            if (flowStatistics != null) {
                amount = flowStatistics.getAmount();
                bounce_amount = flowStatistics.getBounce_amount();
            }
        }

        DecimalFormat df = new DecimalFormat("#0.00");
        String avg_access_time = "0";
        String avg_access_depth = "0";
        if (accessAmount != 0) {
            avg_access_time = new DecimalFormat("#0").format((timeAmount / accessAmount) / 1000);
        }
        if (sessionAmount != 0) {
            avg_access_depth = new DecimalFormat("#0").format(depthAmount / sessionAmount);
        }
        retMap.put("avg_access_time", avg_access_time);
        retMap.put("avg_access_depth", avg_access_depth);

        retMap.put("depthxAxis", depthxAxis);
        retMap.put("depthseries", depthseries);
        retMap.put("timexAxis", timexAxis);
        retMap.put("timeseries", timeseries);
        retMap.put("amount", amount);
        if (amount != 0) {
            retMap.put("bounce_rate", df.format(((double) bounce_amount) / amount * 100));
        } else {
            retMap.put("bounce_rate", "0.00");
        }
        retMap.put("bounce_amount", bounce_amount);
        return Result.success(retMap);
    }



    /**
     * 着陆页流量-着陆页详情tab分页
     *
     * @return
     * @throws Exception
     */
    @PostMapping("/landingPageByNum")
    @ResponseBody
    public Result<Map<String, Object>> landingPageByNum(@RequestBody PageAnalysisDTO pageAnalysisDTO){
        // 处理起始日期
        Map<String, Date> dateMap = ToolUtils.getQueryDate(pageAnalysisDTO.getChooseTime());
        Date startDate = dateMap.get("beginDate");
        Date endDate = dateMap.get("endDate");
        // 获取平台相关code
        List<String> statisticCodeList = getPlatform(pageAnalysisDTO.getPlat_form());
        //logger.info("---------------");
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("sort", pageAnalysisDTO.getSort());
        param.put("start_date", startDate);
        param.put("end_date", endDate);
        param.put("start_num", pageAnalysisDTO.getStart_num());
        param.put("page_size", pageAnalysisDTO.getPage_size());
        String code = "";
        if ("internalFlow".equals(pageAnalysisDTO.getFlow_type())) {
            param.put("plat_form", pageAnalysisDTO.getPlat_form());
            if (StringUtils.isNotEmpty(pageAnalysisDTO.getPlat_form())) {
                param.put("groupSql", " group by page_code,platform_code_total,category_id ");
            } else {
                param.put("groupSql", " group by page_code,category_id ");
            }
            code = "11";
        } else if ("outFlow".equals(pageAnalysisDTO.getFlow_type())) {
            // 如果渠道1不选择 筛选全部外部渠道code
            if (StringUtils.isEmpty(pageAnalysisDTO.getChannel1())) {
                code = "12";
                param.put("groupSql", " group by channel_code ");
            } else {
                // 如果渠道2不选 删选渠道1所有子集code
                if (StringUtils.isEmpty(pageAnalysisDTO.getChannel2())) {
                    code = pageAnalysisDTO.getChannel1().split("_")[1];
                } else {
                    code = pageAnalysisDTO.getChannel2().split("_")[1];
                }
                if ("12h".equals(pageAnalysisDTO.getChannel1().split("_")[1])) {//sem
                    param.put("groupSql", " group by channel_code,page_code ");
                } else {
                    param.put("groupSql", " group by channel_code");
                }
            }
        }
        List<String> channelCodeList = statisticCodeService.getChannelCode(code);
        param.put("statisticCodeList", statisticCodeList.size() == 0 ? null : statisticCodeList);// 平台code
        param.put("channelCodeList", channelCodeList);// 渠道code
        PageInfo<FlowStatisticsVo> tabPageList = flowStatisticsService.landingPageTab(param);
        for (FlowStatisticsVo vo : tabPageList.getList()) {
            StatisticCode statisticParentCode = new StatisticCode();
            statisticParentCode.setCode(vo.getPage_code());
            // 根据条件查询code对象
            statisticParentCode = statisticCodeService
                    .selectStatisticCode(statisticParentCode);
            if (statisticParentCode != null) {
                // 无子集的页面名称取品类名称+页面名称
                if (vo.getPage_code().equals("3XagQ")
                        || vo.getPage_code().equals("3TXDD")
                        || vo.getPage_code().equals("3DaiZ")
                        || vo.getPage_code().equals("3ZhiW")) {
                    String categoryName = CommonParentType
                            .getCategoryShowName(vo.getCategory_id());
                    if (StringUtils.isNotEmpty(categoryName)) {
                        vo.setPage_name(categoryName + "-"
                                + statisticParentCode.getName());// 页面名称
                    } else {
                        vo.setPage_name("其它品类" + vo.getCategory_id() + "-" + statisticParentCode.getName());// 页面名称
                    }
                } else if (vo.getPage_code().startsWith("3PinD")) {
                    vo.setPage_name(statisticParentCode.getName()
                            + statisticParentCode.getParent().getName());// 页面名称
                } else {
                    vo.setPage_name(statisticParentCode.getName());// 页面名称
                }
            }
        }
        Map<String, Object> retMap = new HashMap<String, Object>();
        retMap.put("page", tabPageList);
        return Result.success(retMap);
    }


    /**
     * 着陆页流量-着陆页排名
     *
     * @return
     * @throws ParseException
     */
    @PostMapping("/querylist")
    @ResponseBody
    public Result<Map<String, Object>> querylist(@RequestBody PageAnalysisDTO pageAnalysisDTO){
        // 获取平台相关code
        List<String> StatisticCodeList = new ArrayList<String>();
        if (pageAnalysisDTO.getPlat_form().equals("app")) {
            StatisticCodeList = statisticCodeService.getDeviceCodeApp();
        } else if (pageAnalysisDTO.getPlat_form().equals("ios")) {
            StatisticCodeList = statisticCodeService.getDeviceCodeByLikeName("ios");
        } else if (pageAnalysisDTO.getPlat_form().equals("android")) {
            StatisticCodeList = statisticCodeService.getDeviceCodeByLikeName("android");
        } else if (pageAnalysisDTO.getPlat_form().equals("wap")) {
            StatisticCodeList = statisticCodeService.getDeviceCodeByLikeName("wap");
        } else if (pageAnalysisDTO.getPlat_form().equals("PC")) {
            StatisticCodeList = statisticCodeService.getDeviceCodeByLikeName("PC");
        } else {
            StatisticCodeList = null;
        }
        // 处理起始日期
        Map<String, Date> dateMap = ToolUtils.getQueryDate(pageAnalysisDTO.getChooseTime());
        Date startDate = dateMap.get("beginDate");
        Date endDate = dateMap.get("endDate");
        // 组装查询条件
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("start_date", startDate);
        param.put("end_date", endDate);
        param.put("start_num", pageAnalysisDTO.getCurrentPage());
        param.put("page_size", pageAnalysisDTO.getPage_size());
        String code = "";
        if ("internalFlow".equals(pageAnalysisDTO.getFlow_type())) {
            code = "11";
        } else if ("outFlow".equals(pageAnalysisDTO.getFlow_type())) {
            // 如果渠道1不选择 筛选全部外部渠道code
            if (StringUtils.isEmpty(pageAnalysisDTO.getChannel1())) {
                code = "12";
            } else {
                // 如果渠道2不选 删选渠道1所有子集code
                if (StringUtils.isEmpty(pageAnalysisDTO.getChannel2())) {
                    code = pageAnalysisDTO.getChannel1().split("_")[1];
                } else {
                    code = pageAnalysisDTO.getChannel2().split("_")[1];
                }
            }
        }
        List<String> channelCodeList = statisticCodeService
                .getChannelCode(code);
        param.put("statisticCodeList", StatisticCodeList);// 平台code
        param.put("channelCodeList", channelCodeList);// 渠道code
        PageInfo<FlowStatisticsVo> page = null;
        //查询
        if ("UV".equals(pageAnalysisDTO.getIsmatch())) {
            //	logger.info("----------------sql----start-----------------------");
            page = flowStatisticsService.queryLandingPageList(param);
            //	logger.info("----------------sql----end-----------------------");
        } else {
            page = flowStatisticsService.queryAccessPageList(param);
        }
        List<FlowStatisticsVo> list = page.getList();

        for (FlowStatisticsVo vo : list) {
            StatisticCode statisticParentCode = new StatisticCode();
            statisticParentCode.setCode(vo.getPage_code());
            // 根据条件查询code对象
            statisticParentCode = statisticCodeService
                    .selectStatisticCode(statisticParentCode);
            if (statisticParentCode != null) {
                // 无子集的页面名称取品类名称+页面名称
                if (vo.getPage_code().equals("3XagQ")
                        || vo.getPage_code().equals("3TXDD")
                        || vo.getPage_code().equals("3DaiZ")
                        || vo.getPage_code().equals("3ZhiW")) {
                    String categoryName = CommonParentType
                            .getCategoryShowName(vo.getCategory_id());
                    if (StringUtils.isNotEmpty(categoryName)) {
                        vo.setPage_code(categoryName + "-"
                                + statisticParentCode.getName());// 页面名称
                    } else {
                        vo.setPage_code("其它品类-" + statisticParentCode.getName());// 页面名称
                    }
                } else if (vo.getPage_code().startsWith("3PinD")) {
                    vo.setPage_code(statisticParentCode.getName()
                            + statisticParentCode.getParent().getName());// 页面名称
                } else {
                    vo.setPage_code(statisticParentCode.getName());// 页面名称
                }
            }
            StatisticCode statisticCode = new StatisticCode();
            statisticCode.setCode(vo.getChannel_code());
            // 渠道名称
            statisticCode = statisticCodeService
                    .selectStatisticCode(statisticCode);
            vo.setChannel_code(statisticCode.getName());
            vo.setChannel_parent_code(statisticCode.getParent().getName());
        }

        Map<String, Object> resultMap = new HashMap<String, Object>();
        if (page != null) {
            resultMap.put("count", page.getTotal());
            resultMap.put("flowlist", list);
            resultMap.put("page", page);
        }
        return Result.success(resultMap);
    }

    /**
     * @Title: getChildCodeList
     * @Description: 获取子集code信息
     */
    @PostMapping("/getChildCodeList")
    @ResponseBody
    public Result<Map<String, Object>> getChildCodeList(@RequestParam("parent_id")int parent_id) {
        List<StatisticCode> codeList = statisticCodeService
                .queryChildCodeListByParentId(parent_id);
        Map<String, Object> resultMap = new java.util.HashMap<String, Object>();
        resultMap.put("codeList", codeList);
        return Result.success(resultMap);
    }


    /**
     * 页面流量上下游溯源
     *
     * @return
     * @throws ParseException
     */
    @PostMapping("/conversionlist")
    @ResponseBody
    public Result<Map<String, Object>> channelList(@RequestBody PageAnalysisDTO pageAnalysisDTO){
        List<String> statisticCodeList = null;
        if ("app".equals(pageAnalysisDTO.getPlat_form())) {
            statisticCodeList = statisticCodeService.getDeviceCodeApp();
        } else if (!"".equals(pageAnalysisDTO.getPlat_form())) {
            statisticCodeList = statisticCodeService.getDeviceCodeByLikeName(pageAnalysisDTO.getPlat_form());
        }
        Map<String, Object> param = new HashMap<String, Object>();
        Map<String, Date> dateMap = ToolUtils.getQueryDate(pageAnalysisDTO.getChooseTime());
        Date startDate = dateMap.get("beginDate");
        Date endDate = dateMap.get("endDate");
        if (pageAnalysisDTO.getPage_code().startsWith("3PinD") || pageAnalysisDTO.getPage_code().startsWith("3zhTi")) {
            pageAnalysisDTO.setPage_code(pageAnalysisDTO.getCategory_id());
            pageAnalysisDTO.setCategory_id("");
        }

        param.put("category_id", pageAnalysisDTO.getCategory_id());
        param.put("start_date", startDate);
        param.put("end_date", endDate);
        param.put("page_code", pageAnalysisDTO.getPage_code());
        param.put("statisticCodeList", statisticCodeList);
        param.put("product_id", pageAnalysisDTO.getProductId());
        Map<String, Long> result = flowStatisticsService.queryFlowFromAndToSum(param);
        param.put("pageCurrentNum", pageAnalysisDTO.getPageCurrentNum());
        param.put("pageSize", pageAnalysisDTO.getPage_size());
        param.put("flowType", pageAnalysisDTO.getFlow_type());

        List<FlowStatisticsVo> fromList = flowStatisticsService.queryFlowFromList(param).getList();

        List<FlowStatisticsVo> toList = flowStatisticsService.queryFlowToList(param).getList();

        for (FlowStatisticsVo flowStatisticsVo : fromList) {
            String code = flowStatisticsVo.getParent_page_code() != null ? flowStatisticsVo
                    .getParent_page_code() : "";
            if (code.equals("3XagQ") || code.equals("3TXDD")
                    || code.equals("3DaiZ") || code.equals("3ZhiW")) {
                StatisticCode statisticCode = new StatisticCode();
                statisticCode.setCode(code);
                // 根据条件查询code对象
                statisticCode = statisticCodeService
                        .selectStatisticCode(statisticCode);
                String pageBusinessTypes = "";
                if (statisticCode != null) {
                    pageBusinessTypes = statisticCode.getName();
                }
                // 获得相匹配的品类的信息
                String categoryId = CommonParentType
                        .getCategoryShowName(flowStatisticsVo
                                .getParent_category_id());
                if (StringUtils.isEmpty(categoryId)) {
                    categoryId = "其他";
                }
                flowStatisticsVo.setParent_category_id(categoryId);// 页面名称
                flowStatisticsVo.setParent_page_code(pageBusinessTypes);// 页面业务类型
            } else if (code.startsWith("3PinD") || code.startsWith("3zhTi")
                    || code.startsWith("3SouS")) {
                String category_id1 = "";
                if (code.startsWith("3PinD")) {
                    category_id1 = "3PinD";
                } else if (code.startsWith("3zhTi")) {
                    category_id1 = "3zhTi";
                } else if (code.startsWith("3SouS")) {
                    category_id1 = "3SouS";
                }
                StatisticCode statisticParentCode = new StatisticCode();
                statisticParentCode.setCode(category_id1);
                // 根据条件查询code对象
                statisticParentCode = statisticCodeService
                        .selectStatisticCode(statisticParentCode);
                String categoryId = "";// 页面业务类型
                if (statisticParentCode != null) {
                    categoryId = statisticParentCode.getName();
                }
                StatisticCode statisticCode = new StatisticCode();
                statisticCode.setCode(code);
                // 根据条件查询code对象
                statisticCode = statisticCodeService
                        .selectStatisticCode(statisticCode);
                String pageBusinessTypes = "";
                if (statisticCode != null) {
                    pageBusinessTypes = statisticCode.getName();
                }
                flowStatisticsVo.setParent_page_code(categoryId);// 页面业务类型
                flowStatisticsVo.setParent_category_id(pageBusinessTypes);// 页面名称
            } else {
                StatisticCode statisticCode = new StatisticCode();
                statisticCode.setCode(code);
                // 根据条件查询code对象
                statisticCode = statisticCodeService
                        .selectStatisticCode(statisticCode);
                String pageBusinessTypes = "";
                if (statisticCode != null) {
                    pageBusinessTypes = statisticCode.getName();
                }
                flowStatisticsVo.setParent_page_code(pageBusinessTypes);// 页面业务类型
                flowStatisticsVo.setParent_category_id("");
            }
        }

        for (FlowStatisticsVo flowStatisticsVo : toList) {
            String code = flowStatisticsVo.getPage_code();
            if (code.equals("3XagQ") || code.equals("3TXDD")
                    || code.equals("3DaiZ") || code.equals("3ZhiW")) {
                StatisticCode statisticCode = new StatisticCode();
                statisticCode.setCode(code);
                // 根据条件查询code对象
                statisticCode = statisticCodeService
                        .selectStatisticCode(statisticCode);
                String pageBusinessTypes = "";
                if (statisticCode != null) {
                    pageBusinessTypes = statisticCode.getName();
                }
                // 获得相匹配的品类的信息
                String categoryId = CommonParentType
                        .getCategoryShowName(flowStatisticsVo.getCategory_id());
                if (StringUtils.isEmpty(categoryId)) {
                    categoryId = "其它";
                }
                flowStatisticsVo.setCategory_id(categoryId);// 页面名称
                flowStatisticsVo.setPage_code(pageBusinessTypes);// 页面业务类型
            } else if (code.startsWith("3PinD") || code.startsWith("3zhTi")
                    || code.startsWith("3SouS")) {
                String category_id1 = "";
                if (code.startsWith("3PinD")) {
                    category_id1 = "3PinD";
                } else if (code.startsWith("3zhTi")) {
                    category_id1 = "3zhTi";
                } else if (code.startsWith("3SouS")) {
                    category_id1 = "3SouS";
                }
                StatisticCode statisticParentCode = new StatisticCode();
                statisticParentCode.setCode(category_id1);
                // 根据条件查询code对象
                statisticParentCode = statisticCodeService
                        .selectStatisticCode(statisticParentCode);
                String categoryId = "";// 页面业务类型
                if (statisticParentCode != null) {
                    categoryId = statisticParentCode.getName();
                }
                StatisticCode statisticCode = new StatisticCode();
                statisticCode.setCode(code);
                // 根据条件查询code对象
                statisticCode = statisticCodeService
                        .selectStatisticCode(statisticCode);
                String pageBusinessTypes = "";
                if (statisticCode != null) {
                    pageBusinessTypes = statisticCode.getName();
                }
                flowStatisticsVo.setPage_code(categoryId);// 页面业务类型
                flowStatisticsVo.setCategory_id(pageBusinessTypes);// 页面名称
            } else {
                StatisticCode statisticCode = new StatisticCode();
                statisticCode.setCode(code);
                // 根据条件查询code对象
                statisticCode = statisticCodeService
                        .selectStatisticCode(statisticCode);
                String pageBusinessTypes = "";
                if (statisticCode != null) {
                    pageBusinessTypes = statisticCode.getName();
                }
                flowStatisticsVo.setCategory_id("");// 页面名称
                flowStatisticsVo.setPage_code(pageBusinessTypes);// 页面业务类型
            }
        }

        Long amountF = result.get("amountF");
        Long amountT = result.get("amountT");
        Long amountFO = 0L;
        Long amountTO = 0L;

        DecimalFormat df = new DecimalFormat("#0.00");

        if (fromList != null && !fromList.isEmpty()) {
            for (FlowStatisticsVo flowStatistics : fromList) {
                if (amountF != 0 && flowStatistics.getAmount() > 0) {
                    String rat = df
                            .format(((double) flowStatistics.getAmount() / amountF) * 100);
                    flowStatistics.setRate(rat);
                }
            }
            if("1".equals(pageAnalysisDTO.getPageCurrentNum()) && "".equals(pageAnalysisDTO.getProductId())){
                for (FlowStatisticsVo flowStatistics : fromList) {
                    amountFO += flowStatistics.getAmount();
                }
                FlowStatisticsVo fs = new FlowStatisticsVo();
                fs.setParent_page_code("其它");
                fs.setParent_category_id("");
                fs.setAmount(amountF-amountFO);
                fs.setRate( df.format(((double) fs.getAmount()/ amountF) * 100));
                fromList.add(fs);
            }

        }
        if (toList != null && !toList.isEmpty()) {
            for (FlowStatisticsVo flowStatistics : toList) {
                if (amountT != 0 && flowStatistics.getAmount() > 0) {
                    String rat = df
                            .format(((double) flowStatistics.getAmount() / amountT) * 100);
                    flowStatistics.setRate(rat);
                }
            }
            if("1".equals(pageAnalysisDTO.getPageCurrentNum()) && "".equals(pageAnalysisDTO.getProductId())) {
                for (FlowStatisticsVo flowStatistics : toList) {
                    amountTO += flowStatistics.getAmount();
                }
                FlowStatisticsVo fs = new FlowStatisticsVo();
                fs.setPage_code("其它");
                fs.setCategory_id("");
                fs.setAmount(amountT-amountTO);
                fs.setRate(df.format(((double) fs.getAmount()/ amountT) * 100));
                toList.add(fs);
            }
        }

        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("fromList", new PageInfo<>(fromList));
        resultMap.put("toList", new PageInfo<>(toList));
        resultMap.put("amountF", amountF);
        resultMap.put("amountT", amountT);
        return Result.success(resultMap);
    }

    /**
     * 查询坑位详情
     * @return
     * @throws ParseException
     */
    @PostMapping("/channelDetailList")
    @ResponseBody
    public Result<Map<String, Object>> channelDetailList(@RequestBody PageAnalysisDTO pageAnalysisDTO){
        List<String> statisticCodeList = null;
        if ("app".equals(pageAnalysisDTO.getPlat_form())) {
            statisticCodeList = statisticCodeService.getDeviceCodeApp();
        } else if (!"".equals(pageAnalysisDTO.getPlat_form())) {
            statisticCodeList = statisticCodeService.getDeviceCodeByLikeName(pageAnalysisDTO.getPlat_form());
        }
        Map<String, Object> param = new HashMap<String, Object>();
        Map<String, Date> dateMap = ToolUtils.getQueryDate(pageAnalysisDTO.getChooseTime());
        Date startDate = dateMap.get("beginDate");
        Date endDate = dateMap.get("endDate");
        if (pageAnalysisDTO.getPage_code().startsWith("3PinD") || pageAnalysisDTO.getPage_code().startsWith("3zhTi")) {
            pageAnalysisDTO.setPage_code(pageAnalysisDTO.getCategory_id());
            pageAnalysisDTO.setCategory_id("");
        }
        param.put("category_id", pageAnalysisDTO.getCategory_id());
        param.put("start_date", startDate);
        param.put("end_date", endDate);
        param.put("page_code", pageAnalysisDTO.getPage_code());
        param.put("page", "3PinDuau");//目前只有周边游"3PinDuau"
        param.put("statisticCodeList", statisticCodeList);
        List<FlowStatisticsVo> List = null;
        if("1".equals(pageAnalysisDTO.getType())){
            List = flowStatisticsService.queryFlowDetailFromList(param);
        }else{
            List = flowStatisticsService.queryFlowDetailToList(param);
        }

        Long amountT = 0L;
        DecimalFormat df = new DecimalFormat("#0.00");

        if (List != null && !List.isEmpty()) {
            for (FlowStatisticsVo flowStatistics : List) {
                amountT += flowStatistics.getAmount();
            }
            for (FlowStatisticsVo flowStatistics : List) {
                if (amountT != 0 && flowStatistics.getAmount() > 0) {
                    String rat = df
                            .format(((double) flowStatistics.getAmount() / amountT) * 100);
                    flowStatistics.setRate(rat);
                }
            }
        }
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("list",List);
        return Result.success(resultMap);
    }


    /**
     * 根据业务类型获得页面名称
     *
     * @param categoryId
     * @return
     */
    @PostMapping("/queryPageCode")
    @ResponseBody
    public Result<Map<String, Object>> queryPageCode(@RequestParam("categoryId")String categoryId) {
        Map<String, Object> result = getResult();
        // 当业务类型为"频道""专题"时
        if (categoryId.equals("3PinD") || categoryId.equals("3zhTi")) {
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            // 根据code码获得其子级的code码信息
            List<StatisticCode> codeList = statisticCodeService
                    .getParentAndChildrenLikeCodeObj(categoryId);
            for (StatisticCode statisticCode : codeList) {
                if (statisticCode.getCode().equals("3PinD")
                        || statisticCode.getCode().equals("3zhTi")) {
                    statisticCode.setName("全部");
                }
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("name", statisticCode.getName());
                map.put("value", statisticCode.getCode());
                list.add(map);
            }
            result.put("code", "1");
            result.put("msg", list);
        } else if (categoryId.equals("3XagQ") || categoryId.equals("3TXDD")
                || categoryId.equals("3DaiZ") || categoryId.equals("3ZhiW")) {
            // 通过枚举获得品类的信息
            CommonParentType[] getVSTProduct = CommonParentType.geAllCategory();
            List<CommonParentType> vSTProductlist = Arrays
                    .asList(getVSTProduct);
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            for (CommonParentType CommonParentType : vSTProductlist) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("name", CommonParentType.getShowName());
                map.put("value", CommonParentType.getValue());
                list.add(map);
            }
            result.put("code", "1");
            result.put("msg", list);
        } else {
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            Map<String, Object> map = new HashMap<>();
            map.put("name", "全部");
            map.put("value", "");
            list.add(map);
            result.put("code", "1");
            result.put("msg", list);
        }
        return Result.success(result);
    }



    public List<String> getPlatform(@RequestParam("parent_id")String platform){
        // 获取平台相关code
        List<String> statisticCodeList = new ArrayList<String>();
        if (platform.equals("app")) {
            statisticCodeList = statisticCodeService.getDeviceCodeApp();
        } else if (platform.equals("ios")) {
            statisticCodeList = statisticCodeService.getDeviceCodeByLikeName("ios");
        } else if (platform.equals("android")) {
            statisticCodeList = statisticCodeService.getDeviceCodeByLikeName("android");
        } else if (platform.equals("wap")) {
            statisticCodeList = statisticCodeService.getDeviceCodeByLikeName("wap");
        } else if (platform.equals("PC")) {//增加pc渠道，shibing 20170823
            statisticCodeList = statisticCodeService.getDeviceCodeByLikeName("PC");
        }
        return statisticCodeList;
    }



/*    *//**
     * @param @param  map
     * @param @return 设定文件
     * @return Map<K,V> 返回类型
     * @throws
     * @Title: sortByValueDesc
     * @Description: map降序排序
     *//*
    private static <K, V extends Comparable<? super V>> Map<K, V> sortByValueDesc(
            Map<K, V> map) {
        List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(
                map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
            public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
                return (o2.getValue()).compareTo(o1.getValue());
            }
        });
        Map<K, V> result = new LinkedHashMap<K, V>();
        for (Map.Entry<K, V> entry : list) {
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }*/

    public Map<String, Object> getResult() {
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("code", "-1");
        return result;
    }

}
